<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Validate;
use think\Config;
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Exam extends Backend
{
    
    /**
     * Exam模型对象
     * @var \app\admin\model\Exam
     */
    protected $model = null;
    protected $searchFields = 'ctitle';//默认按该字段模糊搜索

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Exam;
        $this->view->assign("csubjecttypeList", $this->model->getCsubjecttypeList());

        $ichapterid = Db::name('chapter')->field('ichapterid,cchaptername')->select();
        $this->view->assign("ichapterid", $ichapterid);
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // $filter = $this->request->get('filter');
            // $filter = (array)json_decode($filter,true);
            $total = $this->model
                ->with(['chapter'])
                ->where($where)
                ->order('updatetime desc')
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['chapter'])
                ->where($where)
                ->order('updatetime desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                $row->visible(['id','weigh','ctitle','createtime','cdescription','iscore','canswer','csubjecttype','updatetime']);

                $row->visible(['chapter']);
                $row->getRelation('chapter')->visible(['cchaptername']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {

                $params = $this->preExcludeFields($params);

                // csubjecttype 类型:1=判断题,2=单项选择题,3=多选题4，不定项选择题
                $csubjecttype = $params['csubjecttype'];
                switch ($csubjecttype) {
                    case 1:
                        $trueorfalse = $params['trueorfalse'];
                        $trueorfalse=1?$params['canswer'] = '对':$params['canswer'] = '错';

                        $result = $this->model->allowField('ctitle,csubjecttype,canswer,iscore,cdescription,trueorfalse,ichapterid,dchangedate')->isUpdate(false)->save($params);
                        
                        $this->success('添加判断题成功');
                        break;
                    case 2:
                        unset($params['trueorfalse']);
                        unset($params['E']);

                        $canswer = $params['chose_canswer'];
                        $params['canswer'] = $canswer;
                        unset($params['chose_canswer']);
                        $result = $this->model->allowField(true)->validate('Exam.add')->isUpdate(false)->save($params);
                        
                        if ($result === false) {
                            $this->error($this->model->getError());
                        }
                        $this->success('添加单项选择题成功');
                        break;

                    default:

                        unset($params['trueorfalse']);
                        unset($params['chose_canswer']);

                        $canswer = $params['canswer'];
                        $canswer = implode('', $canswer);
                        $params['canswer'] = $canswer;
                        $result = $this->model->validate('Exam.add')->isUpdate(false)->save($params);

                        if ($result === false) {
                            $this->error($this->model->getError());
                        }
                        $this->success('添加多选题成功');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = Db::name('exam')->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                // csubjecttype 类型:1=判断题,2=单项选择题,3=多选题
                $csubjecttype = $params['csubjecttype'];
                switch ($csubjecttype) {
                    case 1:
                        $trueorfalse = $params['trueorfalse'];
                        $trueorfalse=1?$params['canswer'] = '对':$params['canswer'] = '错';

                        $result = $this->model->allowField('ctitle,csubjecttype,canswer,iscore,cdescription,ichapterid,dchangedate')->isUpdate(true)->save($params);
                        
                        $this->success('修改判断题成功');
                        break;
                    case 2:
                        unset($params['trueorfalse']);
                        unset($params['E']);

                        $canswer = $params['chose_canswer'];
                        $params['canswer'] = $canswer;
                        unset($params['chose_canswer']);
                        $result = $this->model->allowField(true)->validate('Exam.add')->isUpdate(true)->save($params);
                        
                        if ($result === false) {
                            $this->error($this->model->getError());
                        }
                        $this->success('修改单项选择题成功');
                        break;

                    default:

                        unset($params['trueorfalse']);
                        unset($params['chose_canswer']);

                        $canswer = $params['canswer'];
                        $canswer = implode('', $canswer);
                        $params['canswer'] = $canswer;
                        $result = $this->model->validate('Exam.add')->isUpdate(true)->save($params);

                        if ($result === false) {
                            $this->error($this->model->getError());
                        }
                        $this->success('修改多选题成功');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['csubjecttype']!==1){
            $row['canswer'] = str_split($row['canswer'] );
            $row['canswer'] = implode(',', $row['canswer']);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function docx2html($source)
    {
        $phpWord = \PhpOffice\PhpWord\IOFactory::load($source);
        $test = '';
        $now_key = '';//当前关键字
        $content = '';
        $comprehension = ['content'=>'','subject_analysis'=>'','question_1'=>'',
        'question_2'=>'','question_3'=>'','question_4'=>'','analysis_1'=>'',
        'analysis_2'=>'','analysis_3'=>'','analysis_4'=>'','answer_1'=>'','answer_2'=>'','answer_3'=>'','answer_4'=>''
        ];//阅读理解的插入数据
        $html = '';
        $count = 0;
        foreach ($phpWord->getSections() as $section) {
            
            foreach ($section->getElements() as $ele1) {
$count +=1;
                if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {

                    $paragraphStyle = $ele1->getParagraphStyle();
                    if ($paragraphStyle) {
                        $html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
                    } else {
                        $html .= '<p>';
                    }

                    foreach ($ele1->getElements() as $ele2) {
                        if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                            $getText = $ele2->getText();
                            // return $getText;

                            $style = $ele2->getFontStyle();
                            $fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
                            $fontSize = $style->getSize();
                            $isBold = $style->isBold();
                            $styleString = '';
                            $fontFamily && $styleString .= "font-family:{$fontFamily};";
                            $fontSize && $styleString .= "font-size:{$fontSize}px;";
                            $isBold && $styleString .= "font-weight:bold;";

                            $now_style_value = sprintf('<span style="%s">%s</span>',
                                $styleString,
                                mb_convert_encoding($getText, 'GBK', 'UTF-8')
                            );
                            

                            if($getText!=='语篇解读'&&$getText!=='QQuestion1'&&$getText!=='QQuestion2'&&$getText!=='QQuestion3'&&$getText!=='QQuestion4'&&$getText!=='阅读理解'&&$getText!=='解析1'&&$getText!=='解析2'&&$getText!=='解析3'&&$getText!=='解析4'&&$getText!=='答案1'&&$getText!=='答案2'&&$getText!=='答案3'&&$getText!=='答案4'){
                                $html .= mb_convert_encoding($now_style_value, 'UTF-8','GBK');
                            }
                            
                        } 
                    }


                }

                $html .= '</p>';
              
                if($getText=='语篇解读'){
                    $comprehension['content'] = $html;
                    $html = '';
                }
                //当前字段是 问题1时 把试题解析内容填入
                if($getText=='QQuestion1'){
                    $comprehension['subject_analysis'] = $html;
                    $html = '';
                }
                if($getText=='QQuestion2'){
                    $comprehension['analysis_1'] = $html;
                    $html = '';
                }
                if($getText=='QQuestion3'){
                    $comprehension['analysis_2'] = $html;
                    $html = '';
                }
                if($getText=='QQuestion4'){
                    //解析的内容获取不了
                    
                    $comprehension['analysis_3'] = $html;
                    $html = '';
                }
                if($getText=='解析3'){
                    $comprehension['answer_3'] = $html;
                    $html = '';
                }
                if($getText=='解析4'){
                    $comprehension['answer_4'] = $html;
                    $html = '';
                }
                
                if($getText=='解析1'){
                    $comprehension['answer_1'] = $html;
                    $html = '';
                }

                if($getText=='解析2'){

                    $comprehension['answer_2'] = $html;
                    $html = '';
                }
                if($getText=='答案1'){
                    $comprehension['question_1'] = $html;
                    $html = '';
                }
              
                if($getText=='答案2'){
                    $comprehension['question_2'] = $html;
                    $html = '';
                }
                if($getText=='答案3'){
                    $comprehension['question_3'] = $html;
                    $html = '';
                }
                if($getText=='答案4'){
                    $comprehension['question_4'] = $html;
                    $html = '';
                }
                if($now_key=='第三次'&&$getText=='解析2'){
                    return $comprehension['answer_2'];
                }
                if($getText=='阅读理解'&&$comprehension['content']!==''&&$now_key=='第三次'){
                    return $comprehension;
                }
                if($getText=='阅读理解'&&$comprehension['content']!==''){
                    
                    //如果没有选项4 就在这里把解析三给添加进去
                    if(empty($comprehension['analysis_3'])){
                        $comprehension['analysis_3'] = $html;
                        $now_key = '第二次';
                    }else{
                        $comprehension['analysis_4'] = $html;
                        $now_key = '第三次';
                    }

                    // Db::name('comprehension')->insert($comprehension);
                    $comprehension = ['content'=>'','subject_analysis'=>'','question_1'=>'',
                    'question_2'=>'','question_3'=>'','question_4'=>'','analysis_1'=>'',
                    'analysis_2'=>'','analysis_3'=>'','analysis_4'=>'','answer_1'=>'','answer_2'=>'','answer_3'=>'','answer_4'=>''
                    ];//阅读理解的插入数据
                    $html = '';
                }

            }

        }
        // return $html;
    }

    public function auto_add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();

            $file_path = $data['file'];
            $file_path = explode(',', $file_path);

            $num = 0;
            foreach($file_path as $file){
                $file = ltrim($file,'/');
                $return_html = $this->docx2html($file);
                dump($return_html);die;
                //$file 文件名，带后缀,带地址目录的
                // $coursesubject_start = strpos($file, 'coursesubject')+13;
                // $point_start = strpos($file, '.');
                // $lenth = $point_start-$coursesubject_start;
                // $ichapterid =  substr($file, $coursesubject_start,$lenth);//ichapterid试卷文件的名称
                
                $file = ltrim($file,'/');//需要去掉/不然说打不开图片
                $fp = fopen($file,"r");
                $str = fread($fp,filesize($file));//指定读取大小，这里把整个文件内容读取出来
                $str = str_replace("\r\n","<br />",$str);

                $array = json_decode($str,true);
                dump($array);die;
                // csubjecttype 类型:1=判断题,2=单选题,3=多选题
                $weigh = count($array);
                $now_desc_id = $desc_id = Db::name('exam')->order('id desc')->value('id');

                foreach ($array as $key => $value) {
                    $title = $value['ctitle'];

                    $src_start = strpos($title, 'src="');
                    $image_start = strpos($title, 'image/');
                    if(!empty($src_start)){
                        $new_title = substr($title, 0,$src_start+5) . Config::get('site.cdnurl') . 'file_dbpath/image/' . substr($title, $image_start+10);
                        $value['ctitle'] = $new_title;
                    }
                   
                    $params = [];
                    $csubjecttype = $value['csubjecttype'];
                    switch ($csubjecttype) {
                        case '判断题':
                            $csubjecttype = 1;

                            break;

                        case '多项选择题':
                            $csubjecttype = 3;
                            break;
                        case '不定项选择题':
                            $csubjecttype = 4;
                            break;
                        case '多选题':
                            $csubjecttype = 3;
                            break;
                        default:
                            $csubjecttype = 2;
                            break;
                    }

                    $cquestion = $value['cquestion'];//答案选项
                    if($csubjecttype==1)
                    {   
                        $answer = $value['canswer'];
                        $params['trueorfalse'] = $answer=='对'?$params['trueorfalse'] = 1:$params['trueorfalse'] = 0;
                        $params['canswer'] = $answer;//答案
                    }else{
                        $b_pos = strpos($cquestion,'B');
                        $c_pos = strpos($cquestion,'C');
                        $d_pos = strpos($cquestion,'D');
                        $e_pos = strpos($cquestion,'E');

                        $params['A'] = substr($cquestion, 2,$b_pos-2);
                        $params['B'] = substr($cquestion, $b_pos+2,$c_pos-$b_pos-2);
                        $params['C'] = substr($cquestion, $c_pos+2,$d_pos-$c_pos-2);

                        if(empty($e_pos)){
                            $params['D'] = substr($cquestion, $d_pos+2);
                        }else{
                            $params['D'] = substr($cquestion, $d_pos+2,$e_pos-$d_pos-2);
                            $params['E'] = substr($cquestion, $e_pos+2);
                        }
                        $params['canswer'] = $value['canswer'];//答案
                    }

                    $params['iscore'] = $value['iscore'];//分数
                    $params['dchangedate'] = $value['dchangedate'];//试卷来源时间

                    //标题过长要截取
                    if(!empty($value['ctitle'])){
                        $ctitle = mb_substr($value['ctitle'], 0,765,'utf-8');
                        $params['ctitle'] = $ctitle;//描述
                    }

                    //描述过长要截取
                    if(!empty($value['cdescription'])){
                        $cdescription = mb_substr($value['cdescription'], 0,765,'utf-8');
                        $params['cdescription'] = $cdescription;//描述
                    }
                    
                    $params['csubjecttype'] = $csubjecttype;//题目类型
                    $params['ichapterid'] = $ichapterid;//题目所属章节id ichapterid试卷文件的名称


                    $exist_ctitle = Db::name('exam')->where(['ctitle'=>$params['ctitle']])->find();

                    if(empty($exist_ctitle)){
                        $now_desc_id += 1;
                        $params['weigh'] = $now_desc_id;
                        $num += 1;
                        $this->model->data($params,true)->isUpdate(false)->save();
                    }
                }
 
            }

            $this->success('录入成功,共录入了'.$num.'条数据');
        }

        return $this->view->fetch();
    }
    

}
